package com.huluspace.jpahibernate.security;

import com.huluspace.jpahibernate.service.JwtAuthService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class JwtFilter extends OncePerRequestFilter {

  @Autowired
  private JwtAuthService jwtAuthService; // 注入JWT鉴权业务类

  /**
   * 重写过滤方法，在每次请求到达控制器之前被执行
   * 从请求中提取JWT，验证，并设置Spring的认证上下文
   */
  @Override
  protected void doFilterInternal(HttpServletRequest request,
                                  HttpServletResponse response,
                                  FilterChain filterChain) throws ServletException, IOException {
    // 从请求头中获取Authorization字段
    String authHeader = request.getHeader("Authorization");
    // 检查请求头是否包含JWT并且符合规范，例如以Bearer开头；
    if (authHeader != null && authHeader.startsWith("Bearer ")) {
      String token = authHeader.substring(7); // 去掉前缀"Bearer"
      try {
        CustomUserDetails userDetails = jwtAuthService.loadUserByToken(token);
        UsernamePasswordAuthenticationToken auth =
            new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        auth.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); // 额外信息
        SecurityContextHolder.getContext().setAuthentication(auth);
      } catch (Exception e) {
        // 处理异常，如日志记录、清理上下文等，临时写法
        throw new RuntimeException("JWT解析失败", e); // 可根据业务抛出合适异常
      }
    }
    filterChain.doFilter(request, response); // 继续处理请求
  }
}
